package com.expert.miniapp.service.impl;

import com.expert.miniapp.dao.UserResourceLibrary;
import com.expert.miniapp.dao.UserResourceLibraryMapper;
import com.expert.miniapp.dto.ResourceStatisticsDTO;
import com.expert.miniapp.dto.UserResourceLibraryDTO;
import com.expert.miniapp.service.UserResourceLibraryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * UserResourceLibraryServiceImpl - 用户资源库业务逻辑实现类
 *
 * @author System
 * @since 2025-10-28
 */
@Service
public class UserResourceLibraryServiceImpl implements UserResourceLibraryService {

    @Autowired
    private UserResourceLibraryMapper userResourceLibraryMapper;

    @Override
    public UserResourceLibrary addResource(String userId, String resourceType, String resourceId, String notes) {
        // 1. 验证参数
        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (resourceType == null || resourceType.trim().isEmpty()) {
            throw new IllegalArgumentException("资源类型不能为空");
        }
        if (resourceId == null || resourceId.trim().isEmpty()) {
            throw new IllegalArgumentException("资源ID不能为空");
        }

        // 2. 检查资源类型是否合法
        Set<String> validTypes = new HashSet<>(Arrays.asList(
                "research_expert", "tech_achievement", "instrument", "laboratory", "other_resource"
        ));
        if (!validTypes.contains(resourceType)) {
            throw new IllegalArgumentException("无效的资源类型: " + resourceType);
        }

        // 3. 检查是否已存在
        String libraryId = userResourceLibraryMapper.existsByUserAndResource(userId, resourceType, resourceId);
        if (libraryId != null) {
            throw new IllegalArgumentException("该资源已在您的资源库中");
        }

        // 4. 创建新记录
        UserResourceLibrary library = new UserResourceLibrary();
        library.setLibraryId(UUID.randomUUID().toString());
        library.setUserId(userId);
        library.setResourceType(resourceType);
        library.setResourceId(resourceId);
        library.setNotes(notes);
        library.setCreatedAt(LocalDateTime.now());

        // 5. 插入数据库
        userResourceLibraryMapper.insert(library);

        return library;
    }

    @Override
    public PageInfo<UserResourceLibraryDTO> getResourceList(String userId, String resourceType, String keyword,
                                                             Integer pageNum, Integer pageSize) {
        // 1. 验证参数
        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 2. 设置分页参数
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);

        // 3. 根据资源类型调用不同的查询方法
        List<UserResourceLibraryDTO> list;

        if (resourceType == null || resourceType.trim().isEmpty() || "all".equalsIgnoreCase(resourceType)) {
            // 查询所有类型
            list = userResourceLibraryMapper.findByUserIdAllTypes(userId, keyword);
        } else {
            // 根据具体类型查询
            switch (resourceType.toLowerCase()) {
                case "research_expert":
                    list = userResourceLibraryMapper.findByUserIdAndType_Expert(userId, keyword);
                    break;
                case "tech_achievement":
                    list = userResourceLibraryMapper.findByUserIdAndType_Achievement(userId, keyword);
                    break;
                case "instrument":
                    list = userResourceLibraryMapper.findByUserIdAndType_Instrument(userId, keyword);
                    break;
                case "laboratory":
                    list = userResourceLibraryMapper.findByUserIdAndType_Laboratory(userId, keyword);
                    break;
                case "other_resource":
                    list = userResourceLibraryMapper.findByUserIdAndType_OtherResource(userId, keyword);
                    break;
                default:
                    throw new IllegalArgumentException("无效的资源类型: " + resourceType);
            }
        }

        return new PageInfo<>(list);
    }

    @Override
    public ResourceStatisticsDTO getStatistics(String userId) {
        // 1. 验证参数
        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 2. 查询统计数据
        List<Map<String, Object>> countList = userResourceLibraryMapper.countByUserIdGroupByType(userId);

        // 3. 构造统计DTO
        ResourceStatisticsDTO statistics = new ResourceStatisticsDTO();
        int total = 0;

        for (Map<String, Object> item : countList) {
            String resourceType = (String) item.get("resource_type");
            Long count = (Long) item.get("count");
            int countInt = count.intValue();

            total += countInt;

            switch (resourceType.toLowerCase()) {
                case "research_expert":
                    statistics.setResearchExpert(countInt);
                    break;
                case "tech_achievement":
                    statistics.setTechAchievement(countInt);
                    break;
                case "instrument":
                    statistics.setInstrument(countInt);
                    break;
                case "laboratory":
                    statistics.setLaboratory(countInt);
                    break;
                case "other_resource":
                    statistics.setOtherResource(countInt);
                    break;
            }
        }

        statistics.setTotal(total);
        return statistics;
    }

    @Override
    public Map<String, Object> checkResourceExists(String userId, String resourceType, String resourceId) {
        // 1. 验证参数
        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (resourceType == null || resourceType.trim().isEmpty()) {
            throw new IllegalArgumentException("资源类型不能为空");
        }
        if (resourceId == null || resourceId.trim().isEmpty()) {
            throw new IllegalArgumentException("资源ID不能为空");
        }

        // 2. 检查是否存在并获取libraryId
        String libraryId = userResourceLibraryMapper.existsByUserAndResource(userId, resourceType, resourceId);
        boolean exists = libraryId != null;

        // 3. 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("exists", exists);
        result.put("libraryId", libraryId);  // 存在时为UUID，不存在时为null

        return result;
    }

    @Override
    public boolean updateNotes(String libraryId, String notes) {
        // 1. 验证参数
        if (libraryId == null || libraryId.trim().isEmpty()) {
            throw new IllegalArgumentException("资源库ID不能为空");
        }

        // 2. 更新备注
        int rows = userResourceLibraryMapper.updateNotes(libraryId, notes);
        return rows > 0;
    }

    @Override
    public boolean deleteResource(String libraryId) {
        // 1. 验证参数
        if (libraryId == null || libraryId.trim().isEmpty()) {
            throw new IllegalArgumentException("资源库ID不能为空");
        }

        // 2. 删除记录
        int rows = userResourceLibraryMapper.deleteById(libraryId);
        return rows > 0;
    }

    @Override
    public UserResourceLibraryDTO getResourceDetail(String libraryId) {
        // 1. 验证参数
        if (libraryId == null || libraryId.trim().isEmpty()) {
            throw new IllegalArgumentException("资源库ID不能为空");
        }

        // 2. 查询资源详情
        UserResourceLibraryDTO dto = userResourceLibraryMapper.findDetailById(libraryId);

        // 3. 检查是否存在
        if (dto == null) {
            throw new RuntimeException("资源库记录不存在");
        }

        return dto;
    }
}
